package queue;

public class ArrayQueue {

    private Object[] m_arrData;
    private int m_iSize;
    private int m_iHead;//最小有数据的位置的下标
    private int m_iTail;//最大有数据的位置的下标

    public ArrayQueue() {
        this(10);
    }

    public ArrayQueue(int iCapacity) {
        this.m_iSize = 0;
        this.m_iHead = 0;
        this.m_iTail = 0;
        this.m_arrData = new Object[iCapacity];
    }

    public void enqueue(Object objData) {
        if (this.m_iSize == this.m_arrData.length) {
            this.reSize(this.m_arrData.length * 2);
        }

        if (this.m_iTail == this.m_arrData.length) {
            this.moveData();
        }

        this.m_arrData[this.m_iTail] = objData;
        this.m_iTail++;
        this.m_iSize++;
    }

    public Object dequeue() {
        if (this.m_iSize == 0) {
            return null;
        }

        Object objResult = this.m_arrData[this.m_iHead];
        this.m_arrData[this.m_iHead] = null;
        this.m_iHead++;
        this.m_iSize--;
        return objResult;
    }

    //重置大小
    private void reSize(int iCapacity) {
        if (iCapacity < 0) {
            return;
        }

        Object[] arrData = new Object[iCapacity];
        for (int i = 0; i < this.m_iSize; i++) {
            arrData[i] = this.m_arrData[i];
        }

        this.m_arrData = arrData;
    }

    //搬移数据
    private void moveData() {
        for (int i = 0; i < this.m_iHead; i++) {
            this.m_arrData[i] = this.m_arrData[i + m_iHead];
        }

        for (int i = this.m_iTail - this.m_iHead; i < this.m_iTail; i++) {
            this.m_arrData[i] = null;
        }

        this.m_iTail = this.m_iTail - this.m_iHead;
        this.m_iHead = 0;
    }

    public void printAll() {
        StringBuilder sb = new StringBuilder();
        for (Object objTemp : this.m_arrData) {
            if (objTemp == null) {
                sb.append("-,");
            } else {
                sb.append(objTemp + ",");
            }
        }
        System.out.println(sb.toString());
    }
}
